Page({
  data: {
    userRole: 'student', // 用户角色：student, teacher, admin
    
    // 学生请假表单数据
    leaveTypes: ['事假', '病假', '休假', '其他'],
    leaveTypeIndex: 0,
    startDate: '',
    endDate: '',
    leaveDays: 0,
    reason: '',
    attachment: '',
    
    // 教师审批数据
    statusFilters: ['全部', '待审批', '已批准', '已拒绝'],
    statusFilterIndex: 0,
    teacherLeaveList: [
      {
        id: 1,
        studentName: '张三',
        studentId: '2023001',
        type: '事假',
        startDate: '2023-09-10',
        endDate: '2023-09-12',
        days: 3,
        reason: '家中有事',
        status: '待审批',
        applyTime: '2023-09-08 14:30'
      },
      {
        id: 2,
        studentName: '李四',
        studentId: '2023002',
        type: '病假',
        startDate: '2023-09-15',
        endDate: '2023-09-18',
        days: 4,
        reason: '感冒发烧',
        status: '待审批',
        applyTime: '2023-09-14 10:15'
      }
    ],
    
    // 管理员数据
    departments: ['全部', '计算机学院', '机械学院', '经济学院'],
    departmentIndex: 0,
    filterDate: '2023-09-15',
    adminLeaveList: [
      {
        id: 1,
        studentName: '张三',
        studentId: '2023001',
        type: '事假',
        startDate: '2023-09-10',
        endDate: '2023-09-12',
        days: 3,
        reason: '家中有事',
        status: '已批准',
        applyTime: '2023-09-08 14:30',
        approver: '王老师'
      },
      {
        id: 2,
        studentName: '李四',
        studentId: '2023002',
        type: '病假',
        startDate: '2023-09-15',
        endDate: '2023-09-18',
        days: 4,
        reason: '感冒发烧',
        status: '待审批',
        applyTime: '2023-09-14 10:15'
      },
      {
        id: 3,
        studentName: '王五',
        studentId: '2023003',
        type: '事假',
        startDate: '2023-09-20',
        endDate: '2023-09-20',
        days: 1,
        reason: '个人事务',
        status: '已拒绝',
        applyTime: '2023-09-18 09:45',
        approver: '李老师'
      }
    ],
    summary: {
      total: 10,
      pending: 3,
      approved: 6,
      rejected: 1
    }
  },
  
  onLoad: function() {
    // 获取用户角色
    const app = getApp();
    if (app.globalData.userInfo && app.globalData.userInfo.role) {
      this.setData({
        userRole: app.globalData.userInfo.role
      });
      
      // 根据角色加载相应数据
      if (this.data.userRole === 'teacher') {
        this.fetchTeacherLeaveList();
      } else if (this.data.userRole === 'admin') {
        this.fetchAdminLeaveList();
        this.fetchLeaveSummary();
      }
    }
    
    // 初始化日期
    this.initDates();
  },
  
  // 初始化日期
  initDates: function() {
    const today = new Date();
    const year = today.getFullYear();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');
    const todayStr = `${year}-${month}-${day}`;
    
    this.setData({
      startDate: todayStr,
      endDate: todayStr,
      filterDate: todayStr
    });
    
    // 计算请假天数
    this.calculateLeaveDays();
  },
  
  // 学生 - 改变请假类型
  changeLeaveType: function(e) {
    this.setData({
      leaveTypeIndex: e.detail.value
    });
  },
  
  // 学生 - 改变开始日期
  changeStartDate: function(e) {
    this.setData({
      startDate: e.detail.value
    });
    this.calculateLeaveDays();
  },
  
  // 学生 - 改变结束日期
  changeEndDate: function(e) {
    this.setData({
      endDate: e.detail.value
    });
    this.calculateLeaveDays();
  },
  
  // 学生 - 计算请假天数
  calculateLeaveDays: function() {
    const startDate = new Date(this.data.startDate);
    const endDate = new Date(this.data.endDate);
    
    // 检查日期是否有效
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      this.setData({
        leaveDays: 0
      });
      return;
    }
    
    // 检查结束日期是否早于开始日期
    if (endDate < startDate) {
      wx.showToast({
        title: '结束日期不能早于开始日期',
        icon: 'none'
      });
      this.setData({
        endDate: this.data.startDate,
        leaveDays: 1
      });
      return;
    }
    
    // 计算天数差
    const diffTime = Math.abs(endDate - startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; // 包含开始和结束日
    
    this.setData({
      leaveDays: diffDays
    });
  },
  
  // 学生 - 输入请假原因
  inputReason: function(e) {
    this.setData({
      reason: e.detail.value
    });
  },
  
  // 学生 - 上传附件
  uploadFile: function() {
    const that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: function(res) {
        const tempFilePath = res.tempFiles[0].path;
        const fileName = res.tempFiles[0].name;
        
        wx.showLoading({
          title: '上传中...',
        });
        
        // 上传文件到服务器
        wx.uploadFile({
          url: 'http://localhost:3000/api/leaves/upload',
          filePath: tempFilePath,
          name: 'file',
          formData: {
            fileName: fileName
          },
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: function(uploadRes) {
            wx.hideLoading();
            try {
              const data = JSON.parse(uploadRes.data);
              if (data.success) {
                that.setData({
                  attachment: data.fileUrl
                });
                wx.showToast({
                  title: '上传成功',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: data.message || '上传失败',
                  icon: 'none'
                });
              }
            } catch (e) {
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              });
            }
          },
          fail: function(error) {
            wx.hideLoading();
            console.error('上传失败:', error);
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        });
      }
    });
  },
  
  // 学生 - 提交请假申请
  submitLeave: function() {
    // 表单验证
    if (!this.data.reason) {
      wx.showToast({
        title: '请输入请假原因',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '提交中...',
    });
    
    // 构建请假数据
    const leaveData = {
      type: this.data.leaveTypes[this.data.leaveTypeIndex],
      startDate: this.data.startDate,
      endDate: this.data.endDate,
      days: this.data.leaveDays,
      reason: this.data.reason,
      attachment: this.data.attachment
    };
    
    // 发送请假申请到服务器
    wx.request({
      url: 'http://localhost:3000/api/leaves',
      method: 'POST',
      data: leaveData,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 201) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          
          // 跳转到请假记录页面
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/qingjiajilu/qingjiajilu'
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 教师 - 获取请假列表
  fetchTeacherLeaveList: function() {
    const status = this.data.statusFilterIndex === 0 ? '' : this.data.statusFilters[this.data.statusFilterIndex];
    
    wx.request({
      url: 'http://localhost:3000/api/leaves/teacher',
      method: 'GET',
      data: {
        status: status
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            teacherLeaveList: res.data
          });
        }
      }
    });
  },
  
  // 教师 - 改变状态筛选
  changeStatusFilter: function(e) {
    const statusIndex = e.detail.value;
    this.setData({
      statusFilterIndex: statusIndex
    });
    
    // 根据筛选条件获取请假列表
    this.fetchTeacherLeaveList();
  },
  
  // 教师 - 查看请假详情
  viewLeaveDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/qingjiaxiangqing/qingjiaxiangqing?id=${id}`
    });
  },
  
  // 教师 - 批准请假
  approveLeave: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '处理中...',
    });
    
    wx.request({
      url: `http://localhost:3000/api/leaves/${id}/approve`,
      method: 'PUT',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          // 更新本地数据
          const teacherLeaveList = this.data.teacherLeaveList;
          const index = teacherLeaveList.findIndex(item => item.id === id);
          
          if (index !== -1) {
            teacherLeaveList[index].status = '已批准';
            this.setData({
              teacherLeaveList: teacherLeaveList
            });
          }
          
          wx.showToast({
            title: '已批准',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 教师 - 拒绝请假
  rejectLeave: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '拒绝原因',
      editable: true,
      placeholderText: '请输入拒绝原因',
      success: (modalRes) => {
        if (modalRes.confirm) {
          const reason = modalRes.content || '无';
          
          wx.showLoading({
            title: '处理中...',
          });
          
          wx.request({
            url: `http://localhost:3000/api/leaves/${id}/reject`,
            method: 'PUT',
            data: {
              rejectReason: reason
            },
            header: {
              'content-type': 'application/json',
              'Authorization': wx.getStorageSync('token')
            },
            success: (res) => {
              wx.hideLoading();
              
              if (res.statusCode === 200) {
                // 更新本地数据
                const teacherLeaveList = this.data.teacherLeaveList;
                const index = teacherLeaveList.findIndex(item => item.id === id);
                
                if (index !== -1) {
                  teacherLeaveList[index].status = '已拒绝';
                  this.setData({
                    teacherLeaveList: teacherLeaveList
                  });
                }
                
                wx.showToast({
                  title: '已拒绝',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: res.data.message || '操作失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.hideLoading();
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },
  
  // 教师 - 跳转到请假审批页面
  navigateToQingjiaShenpi: function() {
    wx.navigateTo({
      url: '/pages/qingjiashenpi/qingjiashenpi'
    });
  },
  
  // 管理员 - 获取请假列表
  fetchAdminLeaveList: function() {
    const department = this.data.departmentIndex === 0 ? '' : this.data.departments[this.data.departmentIndex];
    
    wx.request({
      url: 'http://localhost:3000/api/leaves/admin',
      method: 'GET',
      data: {
        department: department,
        date: this.data.filterDate
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            adminLeaveList: res.data
          });
        } else {
          // 如果请求失败，保留原有数据
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 管理员 - 获取请假统计
  fetchLeaveSummary: function() {
    wx.request({
      url: 'http://localhost:3000/api/leaves/summary',
      method: 'GET',
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            summary: res.data
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取统计数据失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 管理员 - 改变部门筛选
  changeDepartment: function(e) {
    const deptIndex = e.detail.value;
    this.setData({
      departmentIndex: deptIndex
    });
    
    // 根据筛选条件获取请假列表
    this.fetchAdminLeaveList();
  },
  
  // 管理员 - 改变日期筛选
  changeFilterDate: function(e) {
    const date = e.detail.value;
    this.setData({
      filterDate: date
    });
    
    // 根据筛选条件获取请假列表
    this.fetchAdminLeaveList();
  },
  
  // 管理员 - 导出请假数据
  exportLeaveData: function() {
    const department = this.data.departmentIndex === 0 ? '' : this.data.departments[this.data.departmentIndex];
    
    wx.showLoading({
      title: '导出中...',
    });
    
    wx.request({
      url: 'http://localhost:3000/api/leaves/export',
      method: 'GET',
      data: {
        department: department,
        date: this.data.filterDate
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token') // 添加Bearer前缀
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          // 处理文件下载
          const tempFilePath = wx.env.USER_DATA_PATH + '/leave_data.xlsx';
          wx.downloadFile({
            url: res.data.fileUrl,
            filePath: tempFilePath,
            success: function(downloadRes) {
              if (downloadRes.statusCode === 200) {
                wx.openDocument({
                  filePath: tempFilePath,
                  showMenu: true,
                  success: function() {
                    wx.showToast({
                      title: '导出成功',
                      icon: 'success'
                    });
                  },
                  fail: function() {
                    wx.showToast({
                      title: '无法打开文件',
                      icon: 'none'
                    });
                  }
                });
              } else {
                wx.showToast({
                  title: '下载文件失败',
                  icon: 'none'
                });
              }
            },
            fail: function() {
              wx.showToast({
                title: '下载文件失败',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: res.data.message || '导出失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 管理员 - 查看请假详情
  viewLeaveDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/admin/leave/detail/detail?id=${id}`
    });
  }
})